<template>
  <div class="cart">
    <el-container>
      <el-header>
        <el-row>
          <el-col :span="2"
            ><div class="grid-content bg-purple">
              {{ User.username }},欢迎你
            </div></el-col
          >
          <el-col :span="2" :offset="20"
            ><div class="grid-content bg-purple">
              <el-button
                style="font-size: large; color: black"
                type="text"
                @click="returnHome"
                >返回首页</el-button
              >
            </div></el-col
          >
        </el-row>
      </el-header>
      <el-main>
        <div class="left">
          <div
            class="block"
            v-for="(element, index) in tableData"
            :key="element.id"
          >
            <div class="head">
              <!-- 添加复选框 -->
              <el-checkbox
                v-model="checkboxStates[index]"
                @change="updateSelectData"
              >
                <p class="name">{{ element.name }}</p>
              </el-checkbox>
            </div>
            <div class="body">
              <el-image
                class="img_left"
                :src="require(`@/assets/image/p${element.productId}.png`)"
              ></el-image>
              <div class="description_block">
                <p class="description">{{ element.description }}</p>
              </div>
              <div class="price_block">
                <p class="price">¥{{ element.price }}</p>
              </div>
              <div class="num_block">
                数量：<el-input-number
                  v-model="element.num"
                  @change="handleChange(element, $event)"
                  :min="1"
                  :max="99"
                  label="描述文字"
                ></el-input-number>
              </div>
              <div class="delete_block">
                <el-button
                  style="font-size: large; color: black"
                  type="text"
                  @click="deleteProduct(element)"
                  >删除</el-button
                >
              </div>
            </div>
          </div>
        </div>
        <div class="right">
          <div style="margin-bottom: 50px">
            <div
              style="
                float: left;
                font-family: PingFangSC-Semibold;
                font-size: 20px;
                font-weight: 600;
              "
            >
              商品总价
            </div>
            <div style="float: right; font-size: large">
              实际金额以下单页为准
            </div>
          </div>
          <div class="right_body">
            <div
              class="buy_block"
              v-for="element in selecttableData"
              :key="element.id"
            >
              <el-image
                class="img_right"
                :src="require(`@/assets/image/p${element.productId}.png`)"
              ></el-image>
            </div>
          </div>
          <div
            class="right_price_block"
            style="color: rgb(255, 80, 0); font-size: x-large"
          >
            ¥{{ totalPrice }}
          </div>
          <div class="buyproducts" @click="buy">
            <el-button style="width: 150px" type="primary" @click="addCart"
              >结算</el-button
            >
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      User: JSON.parse(sessionStorage.getItem("User")),
      tableData: [],
      // 用于存储复选框状态的数组
      checkboxStates: [],
      selecttableData: [],
      totalPrice: 0,
    };
  },
  async created() {
    this.init();
  },
  methods: {
    async init() {
      try {
        // 等待 getCarts 方法完成
        await this.getCarts();
        // 初始化 checkboxStates 数组
        this.checkboxStates = new Array(this.tableData.length).fill(false);
      } catch (error) {
        console.error("请求错误:", error);
      }
    },
    buy() {
      // 从 selecttableData 数组中提取所有商品的 id
      const data = this.selecttableData.map((item) => item.id);
      // 设置axios请求的headers，指定内容类型为application/json
      const config = {
        headers: {
          "Content-Type": "application/json",
        },
      };
      axios
        .post("http://localhost:8080/users/buyProducts", data,config)
        .then((response) => {
          alert("结算成功");
          this.init();
          this.selecttableData = [];
          this.totalPrice = 0;
        })
        .catch((error) => {
          console.error("请求错误:", error);
        });
    },
    handleChange(element, value) {
      console.log(element.id, ":", value);
      const params = new URLSearchParams({
        id: element.id,
        num: value,
      }).toString();
      axios
        .put(`http://localhost:8080/users/updateCart?${params}`)
        .then((response) => {
          this.updateSelectData();
        })
        .catch((error) => {
          // 请求失败，处理错误
          console.error("Error updating cart", error);
        });
    },
    returnHome() {
      this.$router.push({ name: "ProList" });
    },
    deleteProduct(element) {
      const confirmDelete = confirm("确定将此商品移出购物车吗");
      if (confirmDelete) {
        const params = new URLSearchParams({ id: element.id }).toString();
        axios
          .delete(`http://localhost:8080/users/deleteCart?${params}`)
          .then((response) => {
            this.init();
            this.selecttableData = [];
            this.totalPrice = 0;
          })
          .catch((error) => {
            console.error("请求错误:", error);
          });
      }
    },
    updateSelectData() {
      this.selecttableData = [];
      this.selecttableData = this.tableData.filter(
        (element, index) => this.checkboxStates[index]
      );
      this.totalPrice = this.selecttableData.reduce((sum, item) => {
        return sum + item.num * item.price;
      }, 0);
      console.log("checkboxStates", this.checkboxStates); // 这里应该是 false
      console.log("selecttableData", this.selecttableData);
    },
    async getCarts() {
      const params = new URLSearchParams({
        username: this.User.username, // 使用用户的用户名作为参数
      }).toString();

      try {
        const response = await axios.get(
          `http://localhost:8080/users/getCartList?${params}`
        );
        this.tableData = response.data; // 将返回的数据赋值给 tableData
      } catch (error) {
        console.error("请求错误:", error);
      }
    },
  },
};
</script>


<style scoped>
.el-header {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-main {
  background-color: #e9eef3;
  color: #333;
  display: flex;
  flex-wrap: wrap;
}
.el-container {
  height: 100vh;
}
.left {
  /* background-color: #1bb769; */
  width: 65%;
  height: 100vh;
  margin-top: 50px;
  margin-right: 200px;
  margin-left: 5px;
}
.right {
  /* background-color: #7b9dd3; */
  width: 15%;
  height: 100vh;
  margin-top: 50px;
}
.block {
}
.head {
  display: flex; /* 使用flexbox布局 */
  align-items: flex-start; /* 垂直对齐顶部 */
}
.body {
  display: flex; /* 使用flexbox布局 */
  align-items: flex-start; /* 垂直对齐顶部 */
}
.img_left {
  width: 200px;
  height: 200px;
}
.name {
  color: #11192d;
  font-family: PingFangSC-Semibold;
  font-size: 20px;
  font-weight: 600;
}
.description_block {
  width: 40%;
  margin: 0 auto;
  margin-top: 5%;
}
.description {
  color: #11192d;
  font-family: PingFangSC-Semibold;
  font-size: 20px;
  font-weight: 600;
}
.price {
  color: rgb(255, 80, 0);
  font-size: xx-large;
}
.price_block {
  margin: 0 auto;
  margin-top: 3%;
}
.num_block {
  margin: 0 auto;
  margin-top: 6%;
}
.delete_block {
  margin: 0 auto;
  margin-top: 6%;
}
.img_right {
  width: 80px;
  height: 80px;
}
.right_body {
  width: 100%;
  margin-top: 20px;
  display: flex; /* 使用flexbox布局 */
  flex-wrap: wrap; /* 允许项目在必要时换行 */
  align-items: flex-start; /* 垂直对齐顶部 */
  /* padding: 20px; 添加内边距 */
  /* justify-content: space-between; 使商品在行内均匀分布 */
}
.buy_block {
  margin: 5px;
  width: calc(33% - 10px); /* 每行两个商品，每个商品占据50%的宽度减去间距 */
  box-sizing: border-box; /* 确保边框和内边距包含在宽度内 */
  margin-bottom: 20px; /* 商品之间的垂直间距 */
}
.buyproducts {
  margin-top: 20px;
  width: 70%;
  margin-left: 15%;
}
</style>

